package com.ulook.lookplanet.ui.square;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.base.BaseFragment;
import com.ulook.lookplanet.base.BaseRecyclerAdapter;
import com.ulook.lookplanet.base.BaseViewHolder;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.main.MainActivity;
import com.ulook.lookplanet.main.MainViewModeFactory;
import com.ulook.lookplanet.main.MainViewModel;
import com.ulook.lookplanet.ui.square.article.ArticleActivity;
import com.ulook.lookplanet.ui.square.community.CommunityActivity;
import com.ulook.lookplanet.ui.square.pub.PubActivity;
import com.ulook.lookplanet.widget.ArticleView;
import com.ulook.lookplanet.widget.HotTopicView;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/4/6
 */
public class SquareFragment extends BaseFragment {

    private SquareViewModel squareViewModel;
    private View root;
    private QMUITopBarLayout topBar;
    private LinearLayout hotTopicLayout;
    private QMUIPullLayout pullLayout;
    private RecyclerView recyclerView;
    private int currUserId;
    private BaseRecyclerAdapter<VArticlePreInfo> mAdapter;
    private boolean isRefresh;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        squareViewModel = new ViewModelProvider(this).get(SquareViewModel.class);
        root = inflater.inflate(R.layout.fragment_square, container, false);
        // 消息提示
        squareViewModel.getToastText().observe(getViewLifecycleOwner(), s -> {
            Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
        });
        // 热点话题
        squareViewModel.getHotTopic().observe(getViewLifecycleOwner(), topics ->{
            for(int i = 0; i < topics.size(); i++){
                HotTopicView hotTopicView = new HotTopicView(getActivity());
                hotTopicView.setWidgetData(topics.get(i), currUserId);
                hotTopicLayout.addView(hotTopicView);
            }
        });
        // 推荐动态
        squareViewModel.getLoadData().observe(getViewLifecycleOwner(), loadDataList ->{
            if(isRefresh){
                mAdapter.setData(loadDataList);
                recyclerView.scrollToPosition(0);
            }else {
                mAdapter.append(loadDataList);
            }
        });


        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 获取数据， 初始化
        currUserId = ((MainActivity)getActivity()).getCurrUser().getId();
        initTopBar();
        initData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case ActivityCode.PUB_RESULT_OK :
                break;
        }
    }

    /**
     * 初始化顶部导航栏
     */
    private void initTopBar(){
        QMUIStatusBarHelper.translucent(getActivity());
        topBar = root.findViewById(R.id.square_bar);
        topBar.setTitle(getString(R.string.title_square));
        // 发布按钮
        topBar.addLeftImageButton(R.drawable.ic_pub_article_24dp, 0 ).setOnClickListener(view -> {
            MainViewModel mainViewModel = new ViewModelProvider(getActivity(), new MainViewModeFactory(getActivity().getApplication())).get(MainViewModel.class);
            BaseUser currUser = mainViewModel.getCurrUser().getValue();
            if(currUser instanceof TUser){
                int userId = ((TUser)currUser).getId();
                Intent intent = new Intent(getActivity(), PubActivity.class);
                intent.putExtra("userId", userId);
                startActivityForResult(intent, ActivityCode.PUB_REQUEST);
            }else {
                Toast.makeText(getActivity(), "未登陆账号", Toast.LENGTH_LONG).show();
            }
        });
        // 话题按钮
        topBar.addRightImageButton(R.drawable.ic_squ_topic_bt, 1).setOnClickListener(view -> {
            // 跳转话题分类页面
            Intent intent = new Intent(getActivity(), CommunityActivity.class);
            intent.putExtra("currUserId", currUserId);
            startActivity(intent);
        });
    }

    /**
     * 初始化页面动态
     */
    private void initData(){
        // 热点话题
        hotTopicLayout = root.findViewById(R.id.squ_hot_topic_layout);
        squareViewModel.queryHotTopics();

        // 推荐动态
        pullLayout = root.findViewById(R.id.squ_pull_layout);
        recyclerView = root.findViewById(R.id.squ_recyclerView);

        // 监听 上拉/下拉 动作
        pullLayout.setActionListener(pullAction -> pullLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                    isRefresh = true;
                    squareViewModel.loadData(currUserId, 0);
                } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                    isRefresh = false;
                    squareViewModel.loadData(currUserId, mAdapter.getItemCount());
                }
                pullLayout.finishActionRun(pullAction);
            }
        }, 3000));
        // 设置布局
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });
        // 初始化Adapter
        mAdapter = new BaseRecyclerAdapter<VArticlePreInfo>(getContext(), null) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.recycler_article;
            }
            @Override
            public void bindData(BaseViewHolder holder, int position, VArticlePreInfo item) {
                ArticleView articleView = holder.getItemView(R.id.recycler_article_view);
                articleView.setWidgetData(item, currUserId);
            }
        };
        // 添加item点击动作
        /*mAdapter.setOnItemClickListener((itemView, pos) -> {
            VArticlePreInfo articlePreInfo = mAdapter.getItem(pos);
            // 添加浏览记录
            squareViewModel.addBrowseRecord(currUserId, articlePreInfo.getUid());
            // 跳转详情页面
            Intent intent = new Intent(getActivity(), ArticleActivity.class);
            intent.putExtra("currUserId", currUserId);
            intent.putExtra("article", articlePreInfo);
            startActivity(intent);
        });*/
        recyclerView.setAdapter(mAdapter);
        squareViewModel.loadData(currUserId, 0);
    }

}